package com.gcsoftware.gateway.redis;

import com.gcsoftware.gateway.GWImpl.GwAccessControl;
import com.gcsoftware.gateway.confLoader.LoadGWRbacParam;
import com.gcsoftware.gateway.utils.FileUtils;
import com.gcsoftware.gw.beans.GwAccessRole;
import com.gcsoftware.gw.xml.GwXmlUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.File;

/**
 * Created by qs on 2018/4/11.
 */
public class LoadXml2Redis {
    private RedisUtils redisUtils = getInstance();
    public RedisUtils getInstance() {
        if (null == redisUtils) {
            synchronized (RedisUtils.class) {
                if (null == redisUtils) {
                    redisUtils = new RedisUtils();
                }
            }
        }
        return redisUtils;
    }

    public void init() {
//        RedisUtils.delAllKeys();
        String xmlPath = LoadGWRbacParam.getInstance().getXmlSavePath();
        File file = new File(xmlPath);

        File[] roleFiles = null;
        if (file.exists() && file.isDirectory()) {
            String roleId;
            roleFiles = file.listFiles();
            if (null != roleFiles && roleFiles.length > 0) {
                String fileStr = null;
                for (File fl : roleFiles) {
                    if (fl.getName().endsWith(".xml")) {
                        roleId = fl.getName().replace(".xml", "");
                        fileStr = FileUtils.readFileAsStr(fl);

                        GwAccessRole role = (GwAccessRole) GwXmlUtil.createObject(GwAccessRole.class, fileStr);
                        setAccessRole2Redis(role, fileStr);
                    }
                }
            }
        }
    }

    public void setAccessRole2Redis(GwAccessRole role , String fileStr) {
        redisUtils.del(redisUtils.ROLE_ACCESS_ENDPOINTS_PREFIX + role.getRoleId());
        redisUtils.setString(redisUtils.ROLE_ACCESS_ENDPOINTS_PREFIX + role.getRoleId(),role.getGwAccessInterfs().getGwAccessInterf().toArray().toString());

        redisUtils.del(role.getRoleId());
        redisUtils.setString(role.getRoleId(), StringUtils.isNotBlank(fileStr) ? fileStr : GwXmlUtil.createXML(GwAccessRole.class,role));
        GwAccessControl.putRoleMap(role);
    }
}
